package com.weixin.engine.models.service.impl;

import cn.hutool.core.util.IdUtil;
//import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.weixin.common.dto.UserDTO;
import com.weixin.engine.models.mapper.UserMapper;
import com.weixin.engine.models.pojo.User;
import com.weixin.engine.models.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author: WangChunHui
 * @Date: 2020-04-16 22:37
 * @Description:
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Value("${excel.template}")
    private String templateFileName;

    @Override
    public List<User> findAll() {
        List<User> users = userMapper.selectList(new QueryWrapper<>());
        return users;
    }

    @Override
    public User findById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public void add(User user) {
        userMapper.insert(user);
    }

    @Override
    public void update(User user) {
        userMapper.updateById(user);
    }

    @Override
    public void delById(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public Page<User> selectByCondition(User user, int page, int size) {

//        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.ge(User::getId, user.getId());
//        Page<User> pageResult = userMapper.selectPage(new Page<>(page, size), queryWrapper);

        return lambdaQuery().ge(User::getId, user.getId()).page(new Page<>(page, size));

    }

    //---服务的熔断
    @HystrixCommand(
            fallbackMethod = "paymentCircuitBreaker_fallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), //请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), //时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),//失败率达到多少后跳闸

    }
    )
    @Override
    public String paymentCircuitBreaker(@PathVariable("id") Integer id) {
        if (id < 0) {
            throw new RuntimeException("******id不能为负数");
        }
        String simpleUuid = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "成功调用，流水号是：" + simpleUuid;
    }

    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id) {
        return "id不能为负数，请稍后再试o(╥﹏╥)o" + id;
    }

    @Override
    public void excelExport(HttpServletResponse response) throws IOException {
//        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
//        //https://blog.csdn.net/qq_42426937/article/details/108007160
//        System.out.println(templateFileName);
//        // 方案1 根据对象填充
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
//        String fileName = "score" + simpleDateFormat.format(System.currentTimeMillis()) + ".xlsx";
//        // 这里 会填充到第一个sheet， 然后文件流会自动关闭
//        List<FillData> fillDataList = new ArrayList<>();
//        int count = 50;
//        for (int i = 0; i < count; i++) {
//            FillData fillData = new FillData();
//            fillData.setName("张三" + i + "号");
//            fillData.setChinese(120.0 + i);
//            fillData.setEnglish(141.0 + i);
//            fillData.setMath(119.0 + i);
//            fillData.setNumber(fillData.getChinese() + fillData.getEnglish() + fillData.getMath());
//            fillDataList.add(fillData);
//        }
//        response.setContentType("application/vnd.ms-excel");
//        response.setCharacterEncoding("UTF-8");
//        response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(),
//                StandardCharsets.ISO_8859_1));
//        EasyExcel.write(response.getOutputStream(), FillData.class).withTemplate(templateFileName).sheet().doFill(fillDataList);
    }

    @Override
    public Page<User> pageList(UserDTO userDTO) {
        return baseMapper.searchListPage(new Page<>(userDTO.getPageNum(), userDTO.getPageSize()), userDTO);
    }
}
